<template>
  <van-field
    :class="{'active':focusIdx==config.key,'error':isError==true}"
    v-model="config.value"
    :label="config.label"
    :required="config.must"
    :readonly="config.readonly"
    :disabled="config.disabled"
    :placeholder="config.placeholder"
    @focus="onFocus"
    @blur="onBlur"
  ></van-field>
</template>

<script>
export default {
  data() {
    return {
      focusIdx: null,
      isError: false
    };
  },
  props: ['config'],
  created() {
    if (this.config.key == 'name' && this.config.value) {
      this.$store.commit('SET_NAME', this.config.value);
    }
    if (this.config.key == 'company' && this.config.value) {
      this.$store.commit('SET_COMPANY', this.config.value);
    }
    if (this.config.key == 'post' && this.config.value) {
      this.$store.commit('SET_POST', this.config.value);
    }
    if (this.config.key == 'email' && this.config.value) {
      this.$store.commit('SET_EMAIL', this.config.value);
    }
    if (this.config.key == 'TaxNumber' && this.config.value) {
      this.$store.commit('SET_TAXNUMBER', this.config.value);
    }
    if (this.config.key == 'title' && this.config.value) {
      this.$store.commit('SET_TITLE', this.config.value);
    }
    if (this.config.key == 'CustomVal' && this.config.value) {
      this.$store.commit('SET_CUSTOMVALUE', this.config.value);
    }
  },
  methods: {
    onFocus() {
      this.focusIdx = this.config.key;
      this.isError = false;
    },
    onBlur() {
      this.focusIdx = null;
      if (this.config.must && this.trims(this.config.value) == '') {
        this.isError = true;
      } else {
        this.isError = false;
      }
    }
  },
  watch: {
    'config.value': function(val, oldVal) {
      if (this.trims(val) != '') {
        this.isError = false;
        if (this.config.key == 'name') {
          this.$store.commit('SET_NAME', val);
        }
        if (this.config.key == 'company') {
          this.$store.commit('SET_COMPANY', val);
        }
        if (this.config.key == 'post') {
          this.$store.commit('SET_POST', val);
        }
        if (this.config.key == 'email') {
          this.$store.commit('SET_EMAIL', val);
        }
        if (this.config.key == 'TaxNumber') {
          this.$store.commit('SET_TAXNUMBER', val);
        }
        if (this.config.key == 'title') {
          this.$store.commit('SET_TITLE', val);
        }
        if (this.config.key == 'CustomVal') {
          this.$store.commit('SET_CUSTOMVALUE', val);
        }
      }
    }
  }
};
</script>

<style>
</style>
